<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/* CodeIgniter Controller for use with Minify */
class Minifier extends MY_Controller {
	protected $restricted = false;
	private $files = array();
	private $typ = "js";
	private $admin = false;

	private $conf;
	
	
	function Minifier() {
		parent::MY_Controller();
		
		$this->config->load('minify');
		$this->conf = $this->config->item('minify');
		
		$this->libpath = $this->conf['libpath'];		
		
		ini_set('include_path', $this->conf['path'] . PATH_SEPARATOR . ini_get('include_path') );
    	require_once 'Minify/Build.php';
    	require_once 'Minify.php';
	}

	private function getTemplateFiles() {
		$viewname = $this->config->item('viewname');
		$folder = APPPATH."views/".$viewname."/".$this->typ;
		

		// Check if folder exists fallback: default folder
		if (!file_exists($folder)) {
			$folder = APPPATH."views/".DEFAULTVIEWNAME."/".$this->typ; 
		}

		if ($handle = @opendir($folder)) {
			while (($file = @readdir($handle)) !== false) {
				$parts = explode(".", $file);
				$prefix = (count($parts) > 1) ? $parts[0] : '';
				if (strlen($prefix) > 0 && ($prefix !== 'admin' || $this->admin)) {
					$this->files[] = $folder."/".$file;
				}
			}
			closedir($handle);
		}
	}
	
	private function getFiles() {
		$t = $this->typ;
		if ($this->admin) {
			$t .= "-admin";
		}
					
		$libs = $this->conf[$t];
		foreach ($libs as $lib) {
			$this->files[] = $this->libpath.$lib;
		}
	}
	
	private function serve() {
		//files from config
		$this->getFiles();
		
		//files from template
		$this->getTemplateFiles();
		
		Minify::setCache($this->conf['cache']);
    	Minify::serve('Files', array('files' => $this->files,
					'maxAge' => 31536000 //1 year 
		));
	}
	
	public function js($admin = false) {
		$this->typ = 'js';
		$this->admin = $admin;
		$this->serve();
	}

	public function css($admin = false) {
		$this->typ = 'css';
		$this->admin = $admin;
		$this->serve();
	}
}

?>